package mx.com.theboard.server.Servicios;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.LinkedList;


import mx.com.theboard.client.InterfacesServlets.ReadJson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class ReadJsonImpl extends RemoteServiceServlet implements ReadJson {
	
	public LinkedList<String[]> greetServer(String name) throws IllegalArgumentException {		
		byte[] datos = readFile("http://mklfarha.com/theBoard/objetos.json");
		String datosstr = new String(datos);
		LinkedList<String[]> lista = new LinkedList<String[]>();
		try {
			org.json.JSONArray json = new JSONArray(datosstr);
			for(int i =0;i<json.length();i++){
				JSONObject obj = json.getJSONObject(i);
				String[] arr = new String[5];				
				arr[0] = obj.getString("idobjetos");
				arr[1] = obj.getString("titulo");
				arr[2] = obj.getString("lugar_encontrado");
				arr[3] = obj.getString("ubicacion_actual");
				arr[4] = obj.getString("fecha_reporte");
				lista.add(arr);			
			}
			return lista;
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return lista;
	}
	
	public byte[] readFile(String filename){
		try {
            URL url = new URL(filename);
            InputStream is = url.openStream();
            ByteArrayOutputStream os = new ByteArrayOutputStream();                 
            byte[] buf = new byte[4096];
            int n;                  
            while ((n = is.read(buf)) >= 0) 
                    os.write(buf, 0, n);
            os.close();
            is.close();                     
            byte[] data = os.toByteArray();
            return data;
	    } catch (MalformedURLException e) {
	            e.printStackTrace();
	    } catch (IOException e) {
	            e.printStackTrace();
	    }
	    return null;
	}

	
}
